<template>
  <el-cascader
    change-on-select
    v-model="ids"
    :options="options"
    @change="handleChange"
    :props="props"
    clearable
  />

  <!-- change-on-select -->
</template>
<script>
import * as api from '@/api/components'
import store from '@/store'

export default {
  props: {
    value: {
      type: Array,
      default() {
        return []
      }
    } ,
    isTwo:{
      type: Number,
      default: 1        // ==2 时 只有二级且传 categoryType==1 分类类型（1：产品类目 2：服务产品类目）
    },
    categoryType: {
      type: Number,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: false                 //  // 类型管理列表中修改时传id  回显问题
    },
    classificationId: {
      type: String,
      default: null
    },
    userId: {
      type: String,
      default: null
    },
    apiUrl: {
      type: Number,
      default: 0        //  ==1时  类型管理中添加时  apiUrl更换接口 新增时屏蔽添加过的  修改时屏蔽 添加过的（除本数据外）
    },
  },
  data() {
    return {
      options: [],
      props: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      ids: [] ,
      listLoading: true,
      newVal2: '',
      newVal3: '',
    }
  },
  watch: {
    value(newVal) {
      this.ids = newVal
    },
    classificationId(newVal) {
      this.getOptions(null, '0').then(() => {
        this.filterOptions(this.value)
      })
    }
  },
  created() {
    this.getOptions(null, '0').then(res => {
      this.filterOptions(this.value)
    })
  },
  methods: {
    /* 同步val值变化 */
    emitInput() {
      let arr=[];
      if(this.isTwo == 2){
        arr = [this.ids[0], this.ids[1], this.newVal2]
      }else {
        arr = [this.ids[0], this.ids[1], this.ids[2]]
      }
      this.$emit('input', arr)
    },
    /* 回显值 */
    filterOptions(newVal) {
//      console.log('newVal', newVal)
      if ( newVal == null || newVal.length === 0) {
        // this.resetId()
        this.ids = []
        return
      }
      this.ids = newVal
      if (newVal.length === 2) {
        this.getOptions([newVal[0]], newVal[0])
      } else if (newVal.length === 3) {
        this.getOptions([newVal[0]], newVal[0]).then(res => {
//          console.log('获取第二级', res.data)
          this.newVal2=  newVal[1];
          this.getOptions([newVal[0], newVal[1]], newVal[1]).then(res => {
//            console.log('获取第三级', res.data)
          })
        })
      }
    },
    /* 点击值改变 */
    handleChange(val) {
//      console.log('change', val)
      this.getOptions(val, val[val.length - 1])
      this.emitInput(val[val.length - 1])
    },
    /* 获取options */
    getOptions(val, id) {
      let that = this
      return new Promise(function(resolve, reject) {
        // 如果选择了一级或者二级
        //children为null或者children已经有值，则不再请求接口获取
        if(that.apiUrl == 0){
          if (val !== null && val.length === 1) {
            console.log(that.options)
            for (let i = 0; i < that.options.length; i++) {

              if (that.options[i].id === val[0]) {

                if (
                  that.options[i].children === null ||
                  that.options[i].children.length > 0
                ) {
                  return
                }

              }
            }
          } else if (val !== null && val.length === 2) {
            for (let i = 0; i < that.options.length; i++) {
              if (that.options[i].id === val[0]) {
                for (let j = 0; j < that.options[i].children.length; j++)
                  if (that.options[i].children[j].id === val[1]) {
                    if(that.isTwo == 2){
                      that.newVal2 = that.options[i].children[j].name

                    }
                    if (
                      that.options[i].children[j].children === null ||
                      that.options[i].children[j].children.length > 0
                    ) {

                      return
                    }
                  }
              }
            }
          }
        }

        that.listLoading =true;
        let data = {
          type: val ? val.length + 1 : 1,
          parentId: id,
          categoryType: that.categoryType,
        }
        that.userId && (data.userId = that.userId)
        if(that.isTwo == 2){
          data.categoryType = 1
        }
        if(that.isEdit) {
          data.classificationId = that.classificationId
        }
        if (that.apiUrl == 1) {
          api
            .getCategoryList(data)
            .then(response => {
              that.listLoading =false;
              that.setOptions(val, id, response.data)
              resolve(response)
            })
            .catch(err => {
              reject(err)
              that.listLoading =false;
            })
          return
        }
        api
          .getProductType(data)
          .then(response => {
            that.listLoading =false;
            that.setOptions(val, id, response.data)
            resolve(response)
          })
          .catch(err => {
            reject(err)
            that.listLoading =false;
          })
      })
    },
    /* 设置options */
    setOptions(val, id, data) {
      /*
       * val为null —— 初始化 获一级列表
       * val.length === 1 ['0'] —— 二级
       * val.length === 2 ['0','001']—— 三级
       */

      if (val === null) {
        for (let i = 0; i < data.length; i++) {
          data[i].children = []
        }
        this.options = data
      } else if (val !== null && val.length === 1) {
        for (let i = 0; i < this.options.length; i++) {
          if (this.options[i].id === val[0]) {
            console.log('第一级搜索进来')
            // 如果获取的子级是空，则设置children为null，不再显示下级箭头提示
            if (data.length === 0) {
              this.$message({
                message: '已经没有下级数据拉~',
                type: 'warning',
                duration: 3000
              })
              this.$set(this.options[i], 'children', null)
              return
            }
            console.log('第一级搜索进来，开始添加值')

            for (let i = 0; i < data.length; i++) {

              if(this.isTwo == 2){
                data[i].children = null
              } else {
                data[i].children = []
              }
            }

            this.options[i].children = data
            return
          }
        }
      } else if (val !== null && val.length === 2) {
        for (let i = 0; i < this.options.length; i++) {
          if (this.options[i].id === val[0]) {
            for (let j = 0; j < this.options[i].children.length; j++) {
              if (this.options[i].children[j].id === val[1]) {
               /* if(this.isTwo == 2){
                  this.$set(this.options[i].children[j], 'children', null)
                  return
                }*/
                // 如果获取的子级是空，则设置children为null，不再显示下级箭头提示
                if (data.length === 0) {
                  this.$message({
                    message: '已经没有下级数据拉~',
                    type: 'warning',
                    duration: 3000
                  })
                  this.$set(this.options[i].children[j], 'children', null)
                  return
                }

                this.options[i].children[j].children = data
                return

              }
            }

            return
          }
        }
      }
    }
  }
}
</script>
